package com.xxgc.demo.controller;

import cn.hutool.core.util.IdUtil;
import com.xxgc.demo.controller.pojo.ImageRecyclingPOJO;
import com.xxgc.demo.controller.result.Result;
import com.xxgc.demo.utils.ImageUtil;
import com.xxgc.demo.utils.RedisUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author: Sjy
 * @Date :2023/10/8 - 10 - 08 - 9:26
 * 文件上传下载
 */
@Slf4j
@Tag(name = "文件上传下载中心")
@RestController
@RequestMapping("/file")
public class FilesController {

    //导入redis工具类
    @Autowired
    private RedisUtil redisUtil;
    //图片工具类
    @Autowired
    private ImageUtil imageUtil;

    @Parameters({
            @Parameter(name = "fileImg",description = "图片",required = true),
            @Parameter(name = "model",description = "模块",required = true),
    })
    @Operation(summary = "图片上传",description = "图片")
    @PostMapping("/uploadImg")
    public Result uploadImg(MultipartFile fileImg,String model) throws IOException {
        //判断是不是图片
        String contentType = fileImg.getContentType();
        log.info("contentType:"+contentType);
        //上传类型校验
        if(!contentType.startsWith("image/")){
            return Result.error().msg("图片接口只能上传图片");
        }
        //文件大小校验
        long size = fileImg.getSize();
        //2M
        //扩展，如果是2-5M就压缩到2M以内，如果是大于5M，提示不能大于2M。
        long maxSize = 5 * 1024 * 1024;
        if(size > maxSize){
            return Result.error().msg("图片最大不超过2M");
        }

        //获取文件名
        String filename = fileImg.getOriginalFilename();
        //保存逻辑 本地 OSS COS
        //保存路径
        String path = "C:\\upload\\images\\"+model+"\\";
        //添加时间路径方便做滚动删除或备份
        String timePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        path += timePath + "\\";
        //判断路径再创建文件夹
        File file1 = new File(path);
        if(!file1.exists()){//如果文件路径不存在
            file1.mkdirs();//创建文件路径
        }
        //修改文件名
        String uuid = IdUtil.simpleUUID();
        //提取后缀 从最后一个点开始提取
        String fileSuffix = filename.substring(filename.lastIndexOf("."));
        //缩略图路径
        String path_1 = path + uuid + "_1" + fileSuffix;
        //创建保存路径
        path += uuid + fileSuffix;


        File file = new File(path);

        //-----------------获取图片尺寸-----------------------
        BufferedImage image = ImageIO.read(fileImg.getInputStream());
        int width = image.getWidth() / 2 - 20 - 100;
        int height = image.getHeight() / 2 -20 - 50;

        //写入当前路径

        fileImg.transferTo(file);
        //------------------在右下角加上项目水印-----------------------
        imageUtil.watermark(path,width,height);

        //-------------------图片压缩--------------------------------
        long maxSize4 = 4 * 1024 * 1024;
        long maxSize3 = 3 * 1024 * 1024;
        long maxSize2 = 2 * 1024 * 1024;
        if(size > maxSize4){// 4M - 5M区间
            imageUtil.threadCompressPictures(path,(float) 0.3);
        }else if(size > maxSize3){// 3M - 4M区间
            imageUtil.threadCompressPictures(path,(float) 0.5);
        }else if(size > maxSize2){// 2M - 3M区间
            imageUtil.threadCompressPictures(path,(float) 0.7);
        }


        //虚拟路径映射
        String virtualPath = "/images/"+model+"/"+timePath + "/"+uuid + fileSuffix;

        //-----------------------缩略图--------------------------
        imageUtil.thumbnail(path,path_1);


        //-------------------------垃圾回收-----------------------------
        String key = "recycling_image";
        ImageRecyclingPOJO recyclingPOJO = new ImageRecyclingPOJO(path, path_1, LocalDateTime.now());
        redisUtil.lSet(key,recyclingPOJO);

        String key1 = "recycling:image:"+uuid;
        redisUtil.set(key1,recyclingPOJO,60);

        return Result.ok(virtualPath).msg("图片上传成功");
    }


}
